package com.roger.homecenterscreen.data.location

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.util.concurrent.TimeUnit

/**
 * IP地址获取助手
 */
class IpLocationHelper {
    
    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build()
    
    /**
     * 获取当前设备的公网IP地址和位置信息
     */
    suspend fun getCurrentLocationByIP(): Result<LocationData> = withContext(Dispatchers.IO) {
        return@withContext try {
            // 尝试多个免费的IP地址查询服务，这些服务直接返回位置信息
            val locationServices = listOf(
                "http://ip-api.com/json/?fields=status,country,regionName,city,lat,lon,query",
                "https://ipapi.co/json/",
                "http://www.geoplugin.net/json.gp"
            )
            
            for (service in locationServices) {
                try {
                    val request = Request.Builder()
                        .url(service)
                        .build()
                    
                    val response = client.newCall(request).execute()
                    
                    if (response.isSuccessful) {
                        val responseBody = response.body?.string()
                        if (!responseBody.isNullOrBlank()) {
                            val locationData = parseLocationResponse(service, responseBody)
                            if (locationData != null) {
                                return@withContext Result.success(locationData)
                            }
                        }
                    }
                } catch (e: Exception) {
                    // 继续尝试下一个服务
                    continue
                }
            }
            
            Result.failure(Exception("无法获取IP位置信息"))
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 解析不同服务的位置响应
     */
    private fun parseLocationResponse(service: String, responseBody: String): LocationData? {
        return try {
            when {
                service.contains("ip-api.com") -> {
                    // ip-api.com 响应格式
                    parseIpApiResponse(responseBody)
                }
                service.contains("ipapi.co") -> {
                    // ipapi.co 响应格式
                    parseIpapiCoResponse(responseBody)
                }
                service.contains("geoplugin.net") -> {
                    // geoplugin.net 响应格式
                    parseGeoPluginResponse(responseBody)
                }
                else -> null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析 ip-api.com 响应
     */
    private fun parseIpApiResponse(json: String): LocationData? {
        return try {
            // 简单的JSON解析，避免引入额外依赖
            if (json.contains("\"status\":\"success\"")) {
                val lat = extractJsonValue(json, "lat")?.toDoubleOrNull() ?: 0.0
                val lon = extractJsonValue(json, "lon")?.toDoubleOrNull() ?: 0.0
                val city = extractJsonValue(json, "city") ?: ""
                val regionName = extractJsonValue(json, "regionName") ?: ""
                val country = extractJsonValue(json, "country") ?: ""
                
                LocationData(
                    latitude = lat,
                    longitude = lon,
                    city = city,
                    district = regionName,
                    address = "$country $regionName $city"
                )
            } else null
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析 ipapi.co 响应
     */
    private fun parseIpapiCoResponse(json: String): LocationData? {
        return try {
            val lat = extractJsonValue(json, "latitude")?.toDoubleOrNull() ?: 0.0
            val lon = extractJsonValue(json, "longitude")?.toDoubleOrNull() ?: 0.0
            val city = extractJsonValue(json, "city") ?: ""
            val region = extractJsonValue(json, "region") ?: ""
            val country = extractJsonValue(json, "country_name") ?: ""
            
            LocationData(
                latitude = lat,
                longitude = lon,
                city = city,
                district = region,
                address = "$country $region $city"
            )
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析 geoplugin.net 响应
     */
    private fun parseGeoPluginResponse(json: String): LocationData? {
        return try {
            val lat = extractJsonValue(json, "geoplugin_latitude")?.toDoubleOrNull() ?: 0.0
            val lon = extractJsonValue(json, "geoplugin_longitude")?.toDoubleOrNull() ?: 0.0
            val city = extractJsonValue(json, "geoplugin_city") ?: ""
            val region = extractJsonValue(json, "geoplugin_region") ?: ""
            val country = extractJsonValue(json, "geoplugin_countryName") ?: ""
            
            LocationData(
                latitude = lat,
                longitude = lon,
                city = city,
                district = region,
                address = "$country $region $city"
            )
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 从JSON字符串中提取指定字段的值
     */
    private fun extractJsonValue(json: String, key: String): String? {
        return try {
            val pattern = "\"$key\"\\s*:\\s*\"([^\"]*)\""
            val regex = Regex(pattern)
            val matchResult = regex.find(json)
            matchResult?.groupValues?.get(1)
        } catch (e: Exception) {
            // 尝试数字格式
            try {
                val pattern = "\"$key\"\\s*:\\s*([^,}]*)"
                val regex = Regex(pattern)
                val matchResult = regex.find(json)
                matchResult?.groupValues?.get(1)?.trim()
            } catch (e: Exception) {
                null
            }
        }
    }
} 